<?php

namespace control;
/*
*整改通知类
*/

class rectificationClass extends adIndexClass
{
    private const page = 'rectification';
    private const table = 'rectification';
    private const tableMx = 'rectification_detail';
    private const title = '整改通知';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'    => [
                        'name'  => '通知日期',
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'orderNo'       => [
                        'name'  => "单据编号",
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'target_name'   => [
                        'name'  => "受稽核对象",
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'endDate'       => [
                        'name'  => '整改期限',
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'person_liable' => [
                        'name'  => '整改责任人',
                        'width' => 200,
                    ],
                    'followStid'    => [
                        'name'  => '整改跟进人',
                        'width' => 200,
                    ],
                    'stid'          => [
                        'name'  => '整改通知创建人',
                        'width' => 200,
                    ],
                    'state'         => [
                        'name'  => '状态',
                        'width' => 150,
                        'sort'  => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    '通知日期'  => text(array("name" => "recordDate", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "单据编号"  => text(array("name" => "orderNo")),
                    "受稽核对象" => text(array("name" => "target_name")),
                ],
                [
                    '整改期限'  => text(array("name" => "endDate", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    '整改责任人' => selectMultiple(array("name" => "person_liable", "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid')),
                    "整改跟进人" => selectMultiple(array("name" => "followStid", "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid')),
                ],
                [
                    "状态" => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url    = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo"     => $this->post('orderNo'),//编号
            "target_name" => $this->post('target_name'),//受稽核对象
        );
        //全等查询数组
        $equal = array(
            "state"         => $this->post('state'),//状态
            "person_liable" => $this->post('person_liable'),//整改责任人
            "followStid"    => $this->post('followStid'),//整改跟进人
        );
        $and   = "";
        if ($this->post('recordDate')) {
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'recordDate');
        }
        if ($this->post('endDate')) {
            $and .= self::timeComparison($this->post('endDate'), 'date', 'endDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'recordDate desc,time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate   = array(
                "box"    => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "person_liable":
                    case "followStid":
                    case "stid":
                        $row[] = $array[$key] ? self::findStaff($array[$key]) : '';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id         = $this->get('id') ?: suiji();
        $listId     = explode(',', $this->get('listId'));
        $info       = query(self::table, " id = '" . $id . "' ");
        $fileUpload = new fileUploadClass();

        $button = [];
        if ($this->power(self::page, "edit")) {
            //按钮
            $button[] = [
                'style' => 'li-btn-blue-bg',
                "name"  => "保存",
                "type"  => "点击事件",
                "cla"   => $this->get('cla'),
                "fun"   => "subForm('" . self::page . "EditForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
                "post"  => ["id" => $this->get('id')],
            ];
        }
        $inspectionClass = new inspectionClass();
        $tr[]            = ['', '稽核时间', '稽核项目', '稽核依据', '存在问题'];
        /*****稽核明细*********/
        if (static::isNull(array_filter($listId))) {
            $result = find(array(
                'field' => "id as mxId,detailId,if(audit_date is null,'',concat(audit_date,' ~ ',audit_date_end)) as checkTime,item,basis as mxBasis,question as mxQuestion",
                'table' => self::tableMx . " where orderId = '{$info['id']}' order by list asc"
            ));
            if (count($result['array']) > 0) {
                foreach ($result['array'] as $k => $array) {
                    $array['list'] = $k + 1;
                    $tr[]          = $this->listRow($array);
                }
            } else {
                $tr[] = $this->listRow(['mxId' => self::getId(), 'list' => 1]);
            }
        } else {
            foreach ((array)$listId as $k => $mxid) {
                $inspection_detail = query("inspection_detail", " id = '$mxid' ");
                $inspection        = query("inspection", " id = '" . $inspection_detail['orderId'] . "' ");
                if ($inspection_detail['id']) {
                    $info['target'] = $inspection['target'];
                    $array          = [
                        'list'       => $k + 1,
                        'mxId'       => self::getId(),
                        'detailId'   => $mxid,
                        'checkTime'  => $inspectionClass->timeAssembly($inspection_detail['checkTime'], $inspection_detail['checkTimeEnd']),
                        'item'       => $inspection_detail['item'],
                        'mxBasis'    => $inspection_detail['basis'],
                        'mxQuestion' => $inspection_detail['text'],
                    ];
                    $array['list']  = $k + 1;
                    $tr[]           = $this->listRow($array);
                }
            }
        }
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '详细信息' => [
                [
                    must . "通知日期："  => text(array('name' => 'recordDate', 'laydate' => [], 'value' => $info['recordDate'] ?: $this->date)),
                    must . "受稽核对象：" => selectMultiple(array('table' => 'department', 'multiple' => true, "title" => '请选择', 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'target[]', 'value' => $info['target'])),
                    must . "整改期限："  => text(array('name' => 'endDate', 'laydate' => [], 'value' => $info['endDate'])),
                    must . "整改责任人：" => selectMultiple(array('name' => 'person_liable', 'class' => 'text', 'title' => '请选择', 'table' => 'staff', 'sqlId' => 'stid', 'sqlField' => 'name', 'value' => $info['person_liable'])),
                ],
                [
                    "整改协作人：" => componentClass::staffSelector($info['selector'],'staff')
                ],
                [
                    must . "整改跟进人：" => selectMultiple(array('name' => 'followStid', 'class' => 'text', 'title' => '请选择', 'table' => 'staff', 'sqlId' => 'stid', 'sqlField' => 'name', 'value' => $info['followStid'])),
                ],
                [
                    "备注：" => textarea(array('name' => 'text', 'class' => 'textarea', 'value' => $info['text'])),
                ],
            ]
        ]);
        $body .= $this->editList([
            'class' => 'purchaseMx',
            'title' => '稽核明细',
            'html' => $this->listTable(array('tr' => $tr, 'end' => true)),
        ]);
        $body .= $this->editBlock([
            '附件' => $fileUpload->addFileComponent($info['id'], '整改通知', self::page, self::page . 'EditForm')
        ]);
        $data['html']   = $this->pageEdit([
            "html"  => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $info['id'] ?: $id]),
        ]);

        $data['html'] .= <<<efo

<script>
  //添加一行
         function addRow(e,type){
             $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{type:type},function (res){
                $(e).closest('tr').after(res.data);
                resetNumber($(e).closest('tbody'))
             },'json');
         }
</script>


efo;
        //返回
        return $this->tab($data);
    }

    /**
     * Desc : 稽核明细
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function listRow($data = [])
    {
        $list       = isset($data['list']) ? $data['list'] : '';
        $mxId       = isset($data['mxId']) && $data['mxId'] ? $data['mxId'] : self::getId();
        $field = ['detailId','checkTime','item','mxBasis','mxQuestion'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'listRow',
            'copy' => $field,
        ],320);
        unset($field[0]);
        $field = array_values($field);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $tr         = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRow(this,'mx')"),
            hidden(array('name' => 'mxId[]', 'value' => $mxId)) .
            hidden(array('name' => 'detailId[]', 'value' => $array['detailId'])) .
            text(array('name' => 'checkTime[]', 'laydate' => ['type' => 'datetime', 'range' => '~'], 'value' => $array['checkTime'])),
            textarea(array('name' => 'item[]', 'class' => 'textarea', 'value' => $array['item'])),
            textarea(array('name' => 'mxBasis[]', 'class' => 'textarea', 'value' => $array['mxBasis'])),
            textarea(array('name' => 'mxQuestion[]', 'class' => 'textarea', 'value' => $array['mxQuestion'])),
        ];
        if ($data) {
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     *添加一行
     */
    public function addRow()
    {
        $res          = json_decode($this->listRow(), true);
        $html         = $res['html'];
        $json['data'] = $html;
        return json_encode($json, 320);
    }


    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //附件
        $fileIdArr = $this->post('fileId');
        //稽核明细
        $mxIdArr       = $this->post('mxId') ?? [];
        $detailIdArr   = $this->post('detailId') ?? [];
        $checkTimeArr  = $this->post('checkTime');
        $itemArr       = $this->post('item');
        $mxBasisArr    = $this->post('mxBasis');
        $mxQuestionArr = $this->post('mxQuestion');

        $field           = [
            'recordDate'    => $this->post('recordDate'),
            'target'        => implode(',', (array)$this->post('target')),
            'target_name'   => !static::isNull($this->post('target')) ? checkPlanClass::findDepartment((array)$this->post('target')) : '',
            'endDate'       => $this->post('endDate'),
            'person_liable' => $this->post('person_liable'),
            'selector'      => $this->post('staff')[0] ?? '',//员工选择器
            'followStid'    => $this->post('followStid'),
            'text'          => $this->post('text'),
            'updateTime'    => $this->time
        ];
        $field['member'] = implode(',', componentClass::returnStaffId($field['selector']));
        $annotation      = [
            'recordDate'    => '通知日期',
            'target'        => '受稽核对象',
            'endDate'       => '整改期限',
            'person_liable' => '整改责任人',
            'followStid'    => '整改跟进人',
        ];
        $rules           = [
            'recordDate'    => 'required|date',
            'target'        => 'required',
            'endDate'       => 'required|date',
            'person_liable' => 'required',
            'followStid'    => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请添加稽核明细';
        } else {
            $isPass = true;
            $this->startTrans();
            $where = " id = '$id' ";
            $info  = query(self::table, $where);
            if (!$info['id']) {
                $userNo       = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'ZGTZ' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => '',
                ], $field);
                $field        = array_merge($field, [
                    'id'      => $id,
                    'orderNo' => $userNo,
                    'stid'    => $this->control['stid'],
                    'state'   => '草稿',
                    'time'    => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }


            //添加或更新明细
            if (is_array($mxIdArr)) {
                foreach ($mxIdArr as $k => $nid) {
                    $audit_date = explode('~', $checkTimeArr[$k]);
                    $mxField = [
                        'audit_date'     => count($audit_date) == 2 ? trim($audit_date[0]) : '',
                        'audit_date_end' => count($audit_date) == 2 ? trim($audit_date[1]) : '',
                        'item'           => $itemArr[$k],
                        'basis'          => $mxBasisArr[$k],
                        'question'       => $mxQuestionArr[$k],
                    ];
                    $mx         = query(self::tableMx, " id = '$nid'");
                    if(empty(array_filter($mxField, 'strlen'))) {
                        if (!empty($mx['id'])) delete(array('table' => self::tableMx, 'where' => " id = '$nid'"));
                        continue;
                    }
                    if (!empty($mx['id'])) {
                        //更新
                        $warn = static::update([
                            "table" => self::tableMx,
                            "field" => array_merge(
                                $mxField,
                                [
                                    'recordDate'     => $this->post('recordDate'),
                                    'person_liable'  => $this->post('person_liable')
                                ]
                            ),
                            "where" => " id = '$nid'",
                        ]);
                    } else {
                        $inspection_detail = query("inspection_detail", " id = '$detailIdArr[$k]' ");
                        //新增
                        $warn = static::insert([
                            "table" => self::tableMx,
                            "field" => array_merge($mxField, [
                                'id'         => $nid,
                                'orderId'    => $id,
                                'detailId'   => $detailIdArr[$k],
                                'auditor'    => $inspection_detail['checkStid'],
                                'recordDate'     => $this->post('recordDate'),
                                'person_liable'  => $this->post('person_liable'),
                                'updateTime' => $this->time,
                                'time'       => $this->time
                            ]),
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            if ($isPass && in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                //删除不在此ID中的数据
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name"  => '提交审批',
                "type"  => "弹出层",
                "cla"   => 'audit',
                "fun"   => "operate",
                'style' => 'li-btn-blue-bg',
                "post"  => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name'    => '整改通知',
                    'table'   => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        // 保存函数
                        'save'   => [
                            'cla' => $this->get('cla'),
                            'fun' => 'editEdit'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after'  => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla"  => 'audit',
                "fun"  => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla"  => 'audit',
                "fun"  => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name"  => '审批',
                "type"  => "弹出层",
                "cla"   => 'audit',
                "fun"   => "operate",
                // 以下参数固定格式
                "post"  => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table'   => self::table,
                    // 当前状态
                    'state'   => $info['state'],
                    // 变更
                    'field'   => ['state'],   //变更字段 可多个
                    'value'   => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after'  => [
                            'cla'  => $this->get('cla'),
                            'fun'  => 'useDone',
                            'data' => ['id' => $info['id']],
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla"  => 'audit',
                "fun"  => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table'   => self::table,
                    // 当前状态
                    'state'   => $info['state'],
                    // 变更
                    'field'   => ['state'],   //变更字段 可多个
                    'value'   => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    /**
     * 审核通过，给责任人生成待办
     *
     * @param array $data
     * @return void
     */
    public function useDone(array $data)
    {
        $id    = $data['id'];
        $info  = query(self::table, " id = '$id' ");
        $audit = query('audit', " targetId = '$id' ");
        if (!empty($info['person_liable'])) {
            //给部门负责人发送消息
            message(array(
                "stid"   => $info['person_liable'],
                "type"   => '整改通知',
                "typeId" => $audit['id'],
                "text"   => "您所负责的整改通知审批通过了",
            ));
        }

    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data   = array(
                "id"    => $info['id'],
                "title" => self::title . '详情',
            );
            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
                //按钮
                $button[] = [
                    "name"  => "编辑",
                    "type"  => "顶部页卡",
                    "title" => "编辑用户",
                    "url"   => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                ];
            }
            //反馈措施
            if ($this->power(self::page, "edit") && $info['state'] == '已通过' && $info['workFlow'] == 0 && $this->control['stid'] == $info['person_liable']) {
                if ($this->get('operate') == 'feedback') {
                    //按钮
                    $button[] = [
                        'style' => 'li-btn-blue-bg',
                        "name"  => "保存",
                        "type"  => "点击事件",
                        "cla"   => $this->get('cla'),
                        "fun"   => "subForm('mxForm',root+'control/adIndex.html?cla=" . self::page . "&fun=feedbackEdit')",
                        "post"  => ["id" => $this->get('id')],
                    ];
                } else {
                    //按钮
                    $button[] = [
                        "name"  => "反馈措施",
                        "type"  => "顶部页卡",
                        "title" => "编辑反馈措施",
                        "url"   => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=detail&operate=feedback&id=' . $info['id'],
                    ];
                }
            }
            //整改验证
            if ($this->power(self::page, "edit") && $info['state'] == '已通过' && in_array($info['workFlow'], [1, 2])) {
                if ($this->get('operate') == 'verification') {
                    //按钮
                    $button[] = [
                        'style' => 'li-btn-blue-bg',
                        "name"  => "保存",
                        "type"  => "点击事件",
                        "cla"   => $this->get('cla'),
                        "fun"   => "subForm('mxForm',root+'control/adIndex.html?cla=" . self::page . "&fun=verificationEdit')",
                        "post"  => ["id" => $this->get('id')],
                    ];
                } else {
                    $button[] = [
                        "name" => "关闭整改通知",
                        "type" => "弹出层",
                        "cla"  => $this->get('cla'),
                        "fun"  => "operate",
                        "post" => ["act" => 'close', "id" => $info['id']],
                    ];
                    $button[] = [
                        "name"  => "整改验证",
                        "type"  => "顶部页卡",
                        "title" => "编辑整改验证",
                        "url"   => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=detail&operate=verification&id=' . $info['id'],
                    ];
                }
            }
            //审核按钮
            if (empty($this->get('operate'))) $button = array_merge($button, $this->auditButton($info));
            $inspectionClass = new inspectionClass();
            $result          = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
            $tr[]            = ['稽核时间', '稽核项目', '稽核依据', '存在问题', '整改措施', '整改结果', '完成情况', '核查日期'];
            foreach ($result['array'] as $array) {
                if ($this->get('operate') == 'feedback') {
                    $tr[] = [hidden(array('name' => 'mxId[]', 'value' => $array['id'])) . $inspectionClass->timeAssembly($array['audit_date'], $array['audit_date_end'], '至'), $array['item'], $array['basis'], $array['question'], textarea(array('name' => 'measure[]', 'class' => 'textarea width300', 'value' => $array['measure'])), $array['result'], ($array['completion'] == 1 ? '已完成' : '未完成'), self::null($array['checkDate'])];
                } elseif ($this->get('operate') == 'verification') {
                    $tr[] = [hidden(array('name' => 'mxId[]', 'value' => $array['id'])) . $inspectionClass->timeAssembly($array['audit_date'], $array['audit_date_end'], '至'), $array['item'], $array['basis'], $array['question'], $array['measure'], textarea(array('name' => 'result[]', 'class' => 'textarea width300', 'value' => $array['result'])), radio(["name" => $array['id'] . "completion", 'value' => ['1' => '已完成', '0' => '未完成'], "checked" => $array['completion']]), text(array('name' => 'checkDate[]', 'class' => 'text textPrice', 'laydate' => [], 'value' => $array['checkDate']))];
                } else {
                    $tr[] = [$inspectionClass->timeAssembly($array['audit_date'], $array['audit_date_end'], '至'), $array['item'], $array['basis'], $array['question'], $array['measure'], $array['result'], ($array['completion'] == 1 ? '已完成' : '未完成'), self::null($array['checkDate'])];
                }
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html']   = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        "通知日期"  => $info['recordDate'],
                        "受稽核对象" => $info['target_name'],
                        "整改期限"  => $info['endDate'],
                        "整改负责人"  => $info['person_liable'] ? self::findStaff($info['person_liable']) : '',
                    ),
                    array(
                        "整改协作人" => componentClass::showSelector($info['selector']),
                    ),
                    array(
                        "整改跟进人" => $info['followStid'] ? self::findStaff($info['followStid']) : '',
                    ),
                    array(
                        "备注" => pre($info['text']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '稽核明细',
                'html' => "<div class='purchaseMx'>
                                    <form name='mxForm'>" . hidden(array('name' => 'id', 'value' => $info['id'])) . $this->listTable(array('tr' => $tr, 'showSort' => true)) . "</form>
                                </div>",
            ]);
            $data['html'] .= $this->detailBlock([
                '附件' => fileUploadClass::showFile($info['id'], '整改通知')
            ]);
            $data['html']   .= $this->tableShow(array(
                '系统信息' => array(
                    array(
                        "整改通知编号" => $info['orderNo'],
                        "创建人"    => self::findStaff($info['stid']),
                        "创建时间"   => $info['time'],
                    ),
                    array(
                        "更新时间" => $info['updateTime'],
                        "状态"   => $info['state'],
                    ),
                ),
                '流程'   => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id'])
                    )
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    //整改措施反馈
    public function feedbackEdit()
    {
        $id = $this->post('id');
        //稽核明细
        $mxIdArr    = $this->post('mxId') ?? [];
        $measureArr = $this->post('measure') ?? [];

        $field = [
            'workFlow'   => 1,
            'updateTime' => $this->time
        ];
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请添加整改明细';
        } elseif (empty($id)) {
            $json['warn'] = '对象为空';
        } else {
            $isPass = true;
            $this->startTrans();
            $where        = " id = '$id' ";
            $info         = query(self::table, $where);
            $json['warn'] = static::update([
                "table" => self::table,
                "field" => $field,
                "where" => $where,
            ]);

            //添加或更新明细
            if (is_array($mxIdArr)) {
                foreach ($mxIdArr as $k => $nid) {
                    $mx   = query(self::tableMx, " id = '$nid'");
                    $warn = '';
                    if (!empty($mx['id'])) {
                        //更新
                        $warn = static::update([
                            "table" => self::tableMx,
                            "field" => [
                                'measure'       => $measureArr[$k],
                                'state'         => 1,
                                'feedback_date' => $this->date,
                                'feedback_stid' => $this->control['stid'],
                            ],
                            "where" => " id = '$nid'",
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            if ($isPass && in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }

    //整改验证
    public function verificationEdit()
    {
        $id = $this->post('id');
        //稽核明细
        $mxIdArr      = $this->post('mxId') ?? [];
        $resultArr    = $this->post('result') ?? [];
        $checkDateArr = $this->post('checkDate') ?? [];

        $field = [
            'workFlow'   => 2,
            'updateTime' => $this->time
        ];
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请添加整改明细';
        } elseif (empty($id)) {
            $json['warn'] = '对象为空';
        } else {
            $isPass = true;
            $this->startTrans();
            $where        = " id = '$id' ";
            $info         = query(self::table, $where);
            $json['warn'] = static::update([
                "table" => self::table,
                "field" => $field,
                "where" => $where,
            ]);

            //添加或更新明细
            if (is_array($mxIdArr)) {
                foreach ($mxIdArr as $k => $nid) {
                    $mx   = query(self::tableMx, " id = '$nid'");
                    $warn = '';
                    if (!empty($mx['id'])) {
                        //更新
                        $warn = static::update([
                            "table" => self::tableMx,
                            "field" => [
                                'result'            => $resultArr[$k],
                                'completion'        => $this->post($nid . 'completion'),
                                'checkDate'         => $checkDateArr[$k],
                                'verify_date'       => $this->date,
                                'verify_stid'       => $this->control['stid'],
                                'rectification_num' => $mx['rectification_num'] + 1,
                                'state'             => 2,
                            ],
                            "where" => " id = '$nid'",
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            if ($isPass && in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act  = $this->post('act') ?? '';
        $pwd  = false; // 需要密码
        $word = false;
        $form = $power = '';
        switch ($act) {
            case 'close':
                $act      = 'edit';
                $msg      = '关闭整改通知';
                $title    = '是否确认关闭整改通知？';
                $function = 'close';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                $word     = true;
                break;
            default:
                $act      = 'del';
                $msg      = '删除' . self::title;
                $title    = self::page . 'Delete';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = "不是草稿状态，暂不能删除";
                } else {
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    $all = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($all['array'] as $val) {
                        fileDelete($val['src']);
                        delete(array("table" => 'file', "where" => " id = '$val[id]' "));
                    }
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 关闭整改通知
     * @return bool|string
     */
    public function close()
    {
        $id = $this->post('id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有操作权限";
        } elseif (empty($id)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = '';
            $info = query(self::table, " id = '$id' ");
            if ($info['state'] != '已通过' || !in_array($info['workFlow'], [1, 2])) {
                $warn = "不是已通过状态，或者未反馈，不能进行此操作";
            } else {
                static::update([
                    "table" => self::table,
                    "field" => ['workFlow' => 3],
                    "where" => " id = '$id' ",
                ]);
                static::update([
                    "table" => self::tableMx,
                    "field" => ['state' => 3, 'close_date' => $this->date, 'close_stid' => $this->control['stid']],
                    "where" => " orderId = '$id' ",
                ]);
                //返回
                $warn = "关闭成功";
            }
            $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            //添加日志
            $text .= $this->control['name'] . "操作了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "关闭成功";
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
        }
        return json_encode($json, 320);
    }

}

